package cn.buk.qms.service;

import cn.buk.tms.entity.misc.EntDepartment;
import cn.buk.tms.entity.misc.RoleInfo;
import cn.buk.tms.entity.misc.SmsDetail;
import cn.buk.tms.sc.SearchSmsCriteria;
import cn.buk.tms.dto.SmsDetailDto;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Created with IntelliJ IDEA. User: yfdai Date: 14-10-13 Time: 下午4:01 To change this template use
 * File | Settings | File Templates.
 * @author yfdai
 */
@Component
public class SmsServiceImpl extends BaseAbstractService implements SmsService {

  @Override
  public List<SmsDetailDto> searchSmsDetails(int enterpriseId, int userId, String username, SearchSmsCriteria sc) {
    Set<String> roles = userDao.loadUserRoles(userId);

    if (!roles.contains(RoleInfo.ROLE_ADMIN)) {
      sc.setUsername(username);
    }

    List<SmsDetail> list = smsDao.searchSmsDetails(enterpriseId, sc);

    List<SmsDetailDto> dtos = new ArrayList<>();
    for(SmsDetail smsDetail: list) {
      dtos.add(SmsDetailDto.createdBy(smsDetail));
    }

    return dtos;
  }

  @Override
  public int saveReceivedSms(final int enterpriseId, final String mobile, String content) {
    int retCode = smsDao.saveReceivedSms(enterpriseId, mobile, content, null);

    if (retCode > 0) {
      final String smsContent = "手机号(" + mobile + ")回复：" + content;
      doSendAlert(enterpriseId, smsContent, null, EntDepartment.DEPT_CUSTOMER_SERVICE);
    }

    return retCode;
  }

  @Override
  public int sendSms(String mobile, String smsContent) {
    this.execSendSms(mobile, smsContent);
    return 1;
  }

}
